{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ccb6f21f-353d-44c4-a9fb-bc66b42ee797",
   "metadata": {},
   "source": [
    "1、重命名轴索引\n",
    "Pandas中提供了一个rename()方法来重命名个别列索引或行索引的标签或名\n",
    "\n",
    "rename（mapper = None，index = Nonecolumns = None，axis = \n",
    "None，copy = True，inplace = False，level = None）\r\n",
    "上述方法中参数表示的含义：\r\n",
    "（1）index，columns：表示转换的行索引(index)和列索引(columns)\r\n",
    "（2）axis：表示轴的名称，可以使用index或columns，也可以使用数字0或1\r\n",
    "（3）copy：表示是否复制底层的数据，默认为False\r\n",
    "（4）inplace：默认为False，表示是否返回新的Pandas对，如果设为\r\n",
    "True，则会忽略复制的值\r\n",
    "（5）level：表示级别名称，默认为None，对于多级索引，只重命名指定的标签称 type(err)(msg) from err\r\n",
    "TypeError: agg function failed [how->mean,dtype->object]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "f211b193-25c7-4ffe-9507-a046f1ae2a0d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    A   B   C\n",
      "0  A0  B0  C0\n",
      "1  A1  B1  C1\n",
      "2  A2  B2  C2\n",
      "3  A3  B3  C3\n",
      "......................\n",
      "    a   b   c\n",
      "0  A0  B0  C0\n",
      "1  A1  B1  C1\n",
      "2  A2  B2  C2\n",
      "3  A3  B3  C3\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.DataFrame({\n",
    "    'A':['A0','A1','A2','A3'],\n",
    "    'B':['B0','B1','B2','B3'],\n",
    "    'C':['C0','C1','C2','C3']\n",
    "})\n",
    "print(df)\n",
    "print('......................')\n",
    "# 重命名列索引，并且在原有数据上进行修改\n",
    "a = df.rename(columns={'A':'a','B':'b','C':'c'})\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7b63658e-7d6e-49ec-b6a8-fcdd4d56c7a3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    a   b   c\n",
      "0  A0  B0  C0\n",
      "1  A1  B1  C1\n",
      "2  A2  B2  C2\n",
      "3  A3  B3  C3\n"
     ]
    }
   ],
   "source": [
    "# 还可以根据 str 中提供的使字符串变小写的功能函数 lower() 来重命名索引\n",
    "import pandas as pd\n",
    "df = pd.DataFrame({\n",
    "    'A':['A0','A1','A2','A3'],\n",
    "    'B':['B0','B1','B2','B3'],\n",
    "    'C':['C0','C1','C2','C3']\n",
    "})\n",
    "a = df.rename(str.lower,axis='columns')\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "930b1b61-b602-4485-8fa0-f72689c3c306",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      A   B   C\n",
      "0    A0  B0  C0\n",
      "第一行  A1  B1  C1\n",
      "第二行  A2  B2  C2\n",
      "3    A3  B3  C3\n"
     ]
    }
   ],
   "source": [
    "# 还可以通过 rename() 对行索引进行重命名\n",
    "import pandas as pd\n",
    "df = pd.DataFrame({\n",
    "    'A':['A0','A1','A2','A3'],\n",
    "    'B':['B0','B1','B2','B3'],\n",
    "    'C':['C0','C1','C2','C3']\n",
    "})\n",
    "a = df.rename(index={1:'第一行',2:'第二行'})\n",
    "print(a)   # 为什么带上inplace=true之后结果会为none"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0de2992d-ea3b-452a-b14f-7297242e0683",
   "metadata": {},
   "source": [
    "2、离散化操作\n",
    "有时候我们会碰到这样的需求，例如，将有关年龄的数据进行离散化（分桶）或\n",
    "拆分为“面元”，直白来说，就是将年龄分成几个区间。Pandas 的 cut ()函数能\r\n",
    "实现离散化\n",
    "pandas.cut（x，bins，right = True，labels = None，retbins = \n",
    "False，precision = 3\n",
    "，include_lowest = False，duplicates\r\n",
    "='raise' ）\r\n",
    "上述函数中参数表示含义：\r\n",
    "（1）x：表示要分箱的数组，必须是一维的\r\n",
    "（2）bins：接收int和序列类型的数据，如果传入的是int类型的值则表示在\r\n",
    "x范围内的等宽单元的数量（划分为多少个等间距区间）；如果传的是一个序\r\n",
    "列，则表示将x划分在指定的序列中，若干不在此序列中，则为NaN\r\n",
    "（3）right：是否包含右端点，决定区间的开闭，默认为True\r\n",
    "（4）labels：用于生成区间的标签\r\n",
    "（5）retbins：是否返回bin\r\n",
    "（6）precision：精度，默认保留三位小数\r\n",
    "（7）include_lowest：是否包含左端点\r\n",
    "cut()函数会返回一个Categorical对象，我妈们以将其看作一组表示面元名\r\n",
    "称的字符串，它包含了分组的数量以及不同分类的名称操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "ab451aff-419c-42cf-a509-2f3c8ebdb238",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(18, 25], (18, 25], (18, 25], (25, 35], (18, 25], ..., (35, 60], (25, 35], (60, 100], (35, 60], (25, 35]]\n",
      "Length: 11\n",
      "Categories (5, interval[int64, right]): [(0, 18] < (18, 25] < (25, 35] < (35, 60] < (60, 100]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[[18, 25), [18, 25), [25, 35), [25, 35), [18, 25), ..., [35, 60), [25, 35), [60, 100), [35, 60), [25, 35)]\n",
       "Length: 11\n",
       "Categories (5, interval[int64, left]): [[0, 18) < [18, 25) < [25, 35) < [35, 60) < [60, 100)]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用pandas的cut函数划分年龄组\n",
    "import pandas as pd\n",
    "ages = [20,22,25,27,21,23,37,31,61,45,32]\n",
    "bins = [0,18,25,35,60,100]\n",
    "cuts = pd.cut(ages,bins)\n",
    "print(cuts)\n",
    "\n",
    "# 如果设置左闭右开区间，则可以调用cut函数时传入right=false进行修改\n",
    "pd.cut(ages,bins=bins,right=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e3c7d8a-0234-46b7-bd5b-b9447b47dad5",
   "metadata": {},
   "source": [
    "2、哑变量处理类型数据\n",
    "哑变量又称虚拟变量、名义变量，从名称上看就知道，它是人为虚设的变量，用\n",
    "来反映某个变量的不同类别。使用哑变量处理类别转换，事实上就是将分类变\r\n",
    "转换为哑变量矩阵或指标矩阵，矩阵的值通常用“0”或“1”\n",
    "在Pandas中，可以使用get_dummies()函数对类别特征进行哑变量处理\n",
    "pandas.get_dummies(data, prefix=None, prefix_sep='_', \n",
    "dummy_na=False,columns=None, sparse=False, drop_first=False,\r\n",
    "dtype=None)\r\n",
    "上述函数参数含义：\r\n",
    "（1）data：可接收数组、DataFrame或Series对象\r\n",
    "（2）prefix：表示列名的前缀，默认为None\r\n",
    "（3）prefix_sep：用于附加前缀作为分隔符使用，默认为“_”\r\n",
    "（4）dummy_na：表示是否为NaN值添加一列，默认为False\r\n",
    "（5）columns：表示DataFrame要编码的列名，默认为None\r\n",
    "（6）sparse：表示虚拟列是否是稀疏的，默认为False\r\n",
    "（7）drop_first：是否通过从k个分类级别中删除第一个级获得k-1个分类级\r\n",
    "别，默认为False表示"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "000e5e0a-d2c0-4699-a7c2-c2864bd095fe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   col__司机  col__学生  col__导演  col__工人  col__教师\n",
      "0    False    False    False     True    False\n",
      "1    False     True    False    False    False\n",
      "2     True    False    False    False    False\n",
      "3    False    False    False    False     True\n",
      "4    False    False     True    False    False\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.DataFrame({'职业':['工人','学生','司机','教师','导演']})\n",
    "print(pd.get_dummies(df,prefix=['col_']))  # 哑变量处理"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
